package cn.wolfcode.wms.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.wolfcode.wms.domain.Permission;
import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.mapper.RoleMapper;
import cn.wolfcode.wms.query.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IRoleService;

@Service
public class RoleServiceImpl implements IRoleService {

	@Autowired
	private RoleMapper mapper;
	
	@Override
	public void save(Role role,Long[] ids, Long[] munuIds) {
		//先保存角色
		mapper.save(role);
		//再保存角色和权限关系
		if (ids!=null) {
			for (Long id : ids) {
				mapper.saveRoleAndPermissionRelation(role.getId(),id);
			}
		}
		//再保存角色和菜单关系
		if (munuIds!=null) {
			for (Long mId : munuIds) {
				mapper.saveRoleAndSystemMenuRelation(role.getId(),mId);
			}
		}
	}

	@Override
	public void delete(Long id) {
		//删除关系
		mapper.deleteRoleAndPermissionRelation(id);
		mapper.deleteRoleAndSystemMenuRelation(id);
		//删除角色
		mapper.delete(id);
	}

	@Override
	public void update(Role role,Long[] ids,Long[] munuIds) {
		mapper.deleteRoleAndPermissionRelation(role.getId());
		mapper.deleteRoleAndSystemMenuRelation(role.getId());
		mapper.update(role);
		if (ids!=null) {
			for (Long id : ids) {
				mapper.saveRoleAndPermissionRelation(role.getId(), id);
			}
		}
		if (munuIds!=null) {
			for (Long mId : munuIds) {
				mapper.saveRoleAndSystemMenuRelation(role.getId(),mId);
			}
		}
	}

	@Override
	public Role get(Long id) {
		return mapper.get(id);
	}

	@Override
	public List<Role> list() {
		return mapper.list();
	}

	@Override
	public PageResult query(QueryObject qo) {
		int totalCount = mapper.queryForCount(qo);
		if (totalCount == 0) {
			return new PageResult(qo.getPageSize());
		}
		List<Role> listData= mapper.queryForList(qo);
		return new PageResult(qo.getCurrentPage(),qo.getPageSize(), listData, totalCount);
	}
}
